/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Frame_eliminar_editar.java
 *
 * Created on 5/07/2011, 11:26:04 PM
 */
package prueba_conexion;

import conexion.JmEmpleado;
import conexion.NewHibernateUtil;
import java.util.List;
import java.util.Vector;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;

/**
 *
 * @author JoseManuel
 */
public class Frame_eliminar_editar extends javax.swing.JFrame {

    /** Creates new form Frame_eliminar_editar */
    public Frame_eliminar_editar() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jTextField1 = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jButton3 = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();

        jButton1.setText("Eliminar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Actualizar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(jTable1);

        jLabel1.setText("Ingrese Id de Empleado");

        jButton3.setText("Encontrar Empleado");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jLabel2.setText("Para editar, seleccione la casilla del campo que quiera actualizar, edite, seguidamente deseleccione la casilla,");

        jLabel3.setText("paso seguido presione el boton Actualizar.");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(83, 83, 83)
                .addComponent(jButton3)
                .addContainerGap(227, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addGap(54, 54, 54)
                .addComponent(jButton1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 234, Short.MAX_VALUE)
                .addComponent(jButton2)
                .addGap(183, 183, 183))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 548, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(61, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addComponent(jLabel2)
                .addContainerGap(99, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addComponent(jLabel3)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(33, 33, 33)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton3))
                .addGap(44, 44, 44)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 63, Short.MAX_VALUE)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(99, 99, 99)
                        .addComponent(jButton1)
                        .addGap(30, 30, 30))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton2)
                        .addGap(21, 21, 21))))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        // TODO add your handling code here:
        if (!jTextField1.getText().equals("")){
            runQueryBasedOnId();
        }else { JOptionPane.showMessageDialog(null,"Primero Ingrese id Empleado");
        }
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
        String id,Nom,Ape,Dir,Tel;
        int confirmar = 0;
        id = String.valueOf(jTable1.getValueAt(jTable1.getSelectedRow(),0));
        Nom = String.valueOf(jTable1.getValueAt(jTable1.getSelectedRow(),1));
        Ape = String.valueOf(jTable1.getValueAt(jTable1.getSelectedRow(),2));
        Dir = String.valueOf(jTable1.getValueAt(jTable1.getSelectedRow(),3));
        Tel = String.valueOf(jTable1.getValueAt(jTable1.getSelectedRow(),4));
        confirmar= JOptionPane.showOptionDialog(null,"Desea Actualizar datos de empleado con ID: "+id," ", JOptionPane.YES_NO_CANCEL_OPTION,
        JOptionPane.QUESTION_MESSAGE,null, new Object[] { "SI", "NO"},"SI");
        if (confirmar == 0){
            Editar(Integer.parseInt(id),Nom,Ape,Dir,Tel);
            //JOptionPane.showMessageDialog(null,"Cliente Editado");
        }
        
        if(!jTextField1.getText().trim().equals("")) {
            runQueryBasedOnId();
        }
        
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        String id;
        id = String.valueOf(jTable1.getValueAt(jTable1.getSelectedRow(),0));
        //JOptionPane.showMessageDialog(null,jTable1.getSelectedRow()+","+jTable1.getSelectedColumn()+dato);
        int confirmar = 0;
        confirmar= JOptionPane.showOptionDialog(null,"Esta seguro de eliminar empleado con ID: "+id," ", JOptionPane.YES_NO_CANCEL_OPTION,
        JOptionPane.QUESTION_MESSAGE,null, new Object[] { "SI", "NO"},"SI");
        if (confirmar == 0){
           Eliminar(Integer.parseInt(id)); 
           JOptionPane.showMessageDialog(null,"El empleado ha sido eliminado!");
        }
        
        if(!jTextField1.getText().trim().equals("")) {
            runQueryBasedOnId();
        }
        
    }//GEN-LAST:event_jButton1ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new Frame_eliminar_editar().setVisible(true);
            }
        });
    }
    
     private static String QUERY_BASED_ON_FIRST_NAME="from JmEmpleado a where a.idEmpleado = ";
   // private static String QUERY_BASED_ON_LAST_NAME="from JmEmpleado"/*"from JmEmpleado a where a.apellidoEmpleado like '"*/;

private void runQueryBasedOnId() {
    executeHQLQuery(QUERY_BASED_ON_FIRST_NAME +  jTextField1.getText());
}
    
//private void runQueryBasedOnLastName() {
    //executeHQLQuery(QUERY_BASED_ON_LAST_NAME /*+ Con_ApEmp.getText() + "%'"*/);
//}
    
private void executeHQLQuery(String hql) {
    try {
        Session session = NewHibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();
        Query q = session.createQuery(hql);
        List resultList = q.list();
        displayResult(resultList);
        session.getTransaction().commit();
    } catch (HibernateException he) {
        he.printStackTrace();
        JOptionPane.showMessageDialog(null,"Empleado no existe o vuelva a intentar");
    }
}

private void displayResult(List resultList) {
    Vector tableData = new Vector();
    Vector<String> tableHeaders = new Vector<String>();
    
    tableHeaders.add("IdEmpleado"); 
    tableHeaders.add("NombreEmpleado");
    tableHeaders.add("ApellidoEmpleado");
    tableHeaders.add("DireccionEmpleado");
    tableHeaders.add("TelefonoEmpleado");
    
     Vector<Object> oneRow = null;

    for(Object o : resultList) {
        JmEmpleado empleado = (JmEmpleado)o;
        oneRow = new Vector<Object>();
        //Vector<Object> oneRow = new Vector<Object>();
        oneRow.add(empleado.getIdEmpleado());
        oneRow.add(empleado.getNombreEmpleado());
        oneRow.add(empleado.getApellidoEmpleado());
        oneRow.add(empleado.getDireccionEmpleado());
        oneRow.add(empleado.getTelefonoCasaEmp());
        tableData.add(oneRow);
    }
    jTable1.setModel(new DefaultTableModel(tableData, tableHeaders));
    //DefaultTableModel model = new DefaultTableModel();
    //jTable1.setModel(model);
    //model.setColumnIdentifiers(tableHeaders.toArray());
    //model.addRow(tableData.toArray());
}
 
private void Eliminar(int dato){
         try {
            Session session = NewHibernateUtil.getSessionFactory().openSession();
            org.hibernate.Transaction tx = session.beginTransaction();
            JmEmpleado a = (JmEmpleado) session.load(JmEmpleado.class, dato);
            session.delete(a);
            tx.commit();
        } catch (HibernateException he) {
            he.printStackTrace();
        }
    }
    
    private void Editar(int id,String Nombre,String Apellido ,String Dir, String Tel){
         try {
            Session session = NewHibernateUtil.getSessionFactory().openSession();
            org.hibernate.Transaction tx = session.beginTransaction();
            JmEmpleado a = (JmEmpleado) session.load(JmEmpleado.class, id);
            
            a.setNombreEmpleado(Nombre);
            a.setApellidoEmpleado(Apellido);
            a.setDireccionEmpleado(Dir);
            a.setTelefonoCasaEmp(Tel);
            session.update(a);
            tx.commit();
            JOptionPane.showMessageDialog(null,"Cliente Editado");
        } catch (HibernateException he) {
            he.printStackTrace();
            JOptionPane.showMessageDialog(null,"No se puede modificar");
        }
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration//GEN-END:variables
}
